package com.hu.network.http.request.impl;

import com.alibaba.fastjson.TypeReference;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import com.hu.network.http.bean.InnerRequestBean;
import com.hu.network.http.other.MimeType;
import com.hu.network.http.request.BasePostHttpRequest;
import com.hu.network.util.JsonHelper;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import timber.log.Timber;

/**
 * 说明：
 *
 * @author ： hucanhua
 * @date ： 2017/11/03
 */
public class JsonMutiPostHttpRequestImpl<T> extends BasePostHttpRequest<T> {

    private final InnerRequestBean<Map<String, Object>> innerRequestBean;
    private final TypeReference<T> tTypeReference;

    public JsonMutiPostHttpRequestImpl(InnerRequestBean<Map<String, Object>> innerRequestBean, TypeReference<T> tTypeReference, final ProgressCallback requestCallback, final ProgressCallback responseCallback) {
        super(requestCallback, responseCallback);
        this.innerRequestBean = innerRequestBean;
        this.tTypeReference = tTypeReference;
    }

    @Override
    protected RequestBody getParams() {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Map.Entry<String, Object> entry : innerRequestBean.getParams().entrySet()) {
            Object value = entry.getValue();
            if (value instanceof File) {
                builder.addFormDataPart(entry.getKey(), ((File) value).getName(), getRequestBody(value, MimeType.FILE));
            } else {
                builder.addFormDataPart(entry.getKey(), JsonHelper.toJsonString(entry.getValue()));
            }
        }
        return builder.build();
    }

    @Override
    protected String getUrl() {
        return innerRequestBean.getUrl();
    }

    @Override
    protected T dealResponse(ResponseBody body) throws IOException {
        String bodyStr = body.string();
        Timber.d("数据:%s",bodyStr);
        return JsonHelper.parseObject(bodyStr, tTypeReference);
    }

    @Override
    public boolean useHttps() {
        return innerRequestBean.isHttps();
    }
}
